package cn.szzsi._web;

import cn.szzsi._Config;
import cn.szzsi.common.sms.SmsEmayUtil;
import cn.szzsi.interceptor.WechatLoginInterceptor;
import cn.szzsi.service.UserBalanceService;
import cn.szzsi.service.UserPointDetailService;
import cn.szzsi.common.bean.dto.Msg;
import cn.szzsi.common.kit.*;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.Message;
import cn.szzsi.common.model.SiteConfig;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;
import com.sun.mail.smtp.DigestMD5;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import java.math.BigDecimal;

/**
 * 前台类 - 用户中心
 * Created by haotian on 2016/10/14.
 */
public class CustomerCenterController extends BaseWebController<Member> {
    private String path;

    @Before(WechatLoginInterceptor.class)
    public void index() {//用户中心
        Member member = getAttr("loginMember");
        setAttr("loginMember", member);
        if(member==null){
            render("/template/default/html/fansindex.html");
        }else{
            //setAttr("unreadMessageCount", Message.dao.getUnreadMessageCount(member));
            //查看该会员今天有没有签到
            if (UserPointDetailService.service.checkIfUserSign(member)) {
                setAttr("alreadySign", "alreadySign");
            }
            setAttr("totalProfit", UserBalanceService.service.getBalance(member));
            //getTemplatePath(shopId, "fansindex");
            wapTemplatePath("fansindex.html");
        }


    }

    /**
     * 本方法主要是新增用户绑定手机号
     * 手机号存在,直接把微信用户信息更新到现有的手机号中
     * 手机号不存在,新增一个用户
     */
    @Clear
    public void  phoneapplyForRegister(){
        final String phone=getPara("phone");
        String captcha=getPara("phoneCaptcha");
        String password=getPara("password");
        /*if(StrKit.notBlank(phone)&&!RegexUtils.checkMobile(phone)){
            renderJson(Ret.fail("info","请输入正确的手机号"));
            return;
        }*/
        if(CacheKit.get("sms",phone)==null){
            renderJson(Ret.fail("info","手机验证码已过期,请重新获取"));
            return;
        }
        if(!captcha.equals(CacheKit.get("sms",phone).toString())){
            renderJson(Ret.fail("info","手机验证码不正确"));
            return;
        }
        JSONObject userJson=getSessionAttr(Member.USER_JSON);
        final String nickname = userJson.getString("nickname");
        final String sex = userJson.getString("sex");
        final String country = userJson.getString("country");
        final String province = userJson.getString("province");
        final String city = userJson.getString("city");
        final String headimgurl = userJson.getString("headimgurl");
        final String privilege = userJson.getString("privilege");
        final String openid=userJson.getString("openid");
        final String unionid=userJson.getString("unionid");
        Member member=Member.dao.getByPhone(phone);
        if(member==null){//手机号不存在-->新增
            Member memberByUnionid=Member.dao.getByUnionid(unionid);
            if(memberByUnionid!=null){//unionid存在-->更新
                memberByUnionid.set("sex", sex);
                memberByUnionid.set("country", country);
                memberByUnionid.set("province", province);
                memberByUnionid.set("city", city);
                if(StrKit.notBlank(password)){
                    memberByUnionid.set("password", DigestUtils.md5Hex(password));
                }
                memberByUnionid.set("headimgurl", headimgurl);
                memberByUnionid.set("privilege", privilege);
                memberByUnionid.set("username", nickname);
                memberByUnionid.set("openid",openid);
                memberByUnionid.setUnionid(unionid);
                memberByUnionid.setPhone(phone);
                memberByUnionid.update();
            }else{//新增
                _Config.fixedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                           Member addMember= Member.saveMemberInfo("0", "0", openid, nickname, sex, country, province, city, headimgurl, privilege, unionid, CommonUtil.PLATFROM_FLAG, "", IdGen.get().nextId(10));
                           addMember.setPhone(phone);
                           addMember.update();
                        }catch (Exception e){
                            Member addMember= Member.saveMemberInfo("0", "0", openid, "", sex, country, province, city, headimgurl, privilege, unionid, CommonUtil.PLATFROM_FLAG, "", IdGen.get().nextId(10));
                            addMember.setPhone(phone);
                            addMember.update();
                        }
                    }
                });
            }


            Member saveMember = Member.dao.getByOpenid(openid);//上一步保存的信息会员
            if(StrKit.notBlank(password)){
                saveMember.setPassword(DigestUtils.md5Hex(password));
                saveMember.update();
            }

            setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, saveMember.getId());// 写入会员登录Session
        }else{//手机号存在-->更新信息
            member.set("sex", sex);
            member.set("country", country);
            member.set("province", province);
            member.set("city", city);
            if(StrKit.notBlank(password)){
                member.set("password", DigestUtils.md5Hex(password));
            }
            member.set("headimgurl", headimgurl);
            member.set("privilege", privilege);
            member.set("username", nickname);
            member.set("openid",openid);
            member.setUnionid(unionid);
            member.update();

            setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, member.getId());// 写入会员登录Session
            setAttr("loginMember", member);
        }
        renderJson(Ret.ok("info","验证成功!"));


    }

    /**
     * 本方法主要是新增用户绑定手机号
     * 手机号存在,直接把微信用户信息更新到现有的手机号中
     * 手机号不存在,新增一个用户
     */
    @Clear
    public void  phoneapplyForLogin(){
        String phone=getPara("phone");
        String captcha=getPara("phoneCaptcha");
        String password=getPara("password");
        Member member=getSessionAttr("member");
        /*if(StrKit.notBlank(phone)&&!RegexUtils.checkMobile(phone)){
            renderJson(Ret.fail("info","请输入正确的手机号"));
            return;
        }*/
        if(CacheKit.get("sms",phone)==null){
            renderJson(Ret.fail("info","手机验证码已过期,请重新获取"));
            return;
        }
        if(!captcha.equals(CacheKit.get("sms",phone).toString())){
            renderJson(Ret.fail("info","手机验证码不正确"));
            return;
        }
        if(member==null){
            renderJson(Ret.fail("info","参数错误"));
            return;
        }
        if(StrKit.notBlank(password)){
            member.setPassword(DigestUtils.md5Hex(password));
        }
        member.setPhone(phone);
        member.update();
        setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, member.getId());// 写入会员登录Session
        setAttr("loginMember", member);
        renderJson(Ret.ok("info","验证成功!"));


    }

    //我的二维码
    public void mycode() {
        render(CommonUtil.getRealTemplatePath(path, "mycode.html"));
    }

    //绑定手机号码
    @Clear
    public void phoneapply() {
        Member member = getLoginMember();
        String shopId = getPara("shopId");
        path = CommonUtil.getPathByUidAndType(shopId, CommonUtil.isMobileDevice(getRequest()));//获取模板路径
        setAttr("loginMember", member);
        setAttr("base", getRequest().getContextPath());
        getTemplatePath(shopId, "phone_apply");
    }

    //发送手机号码
    //发送手机号码
    @Clear
    public void sendSms(){
        String phone = getPara("phone");
        if(StrKit.isBlank(phone)){
            renderJson(Ret.fail("info","请输入正确的手机号"));
            return;
        }
        /*if(StrKit.notBlank(phone)&&!RegexUtils.checkMobile(phone)){
            renderJson(Ret.fail("info","请输入正确的手机号"));
            return;
        }*/
        //同一个手机号限制一分钟之内只能发送一条
        Long lastTimeMillis = CacheKit.get("sms_last_time",phone);
        if(lastTimeMillis!=null){
            Long currentTimeMillis=System.currentTimeMillis();
            if((currentTimeMillis-lastTimeMillis)<60000){
                renderJson(Ret.fail("info","您的操作过于频繁,请稍后再试!!"));
                return;
            }

        }
        //同一个手机号限制一分钟之内只能发送一条
        //【微米荟商城】您的验证码:686260 ，请勿泄露！感谢您的使用！
        String captcha = CommonUtil.getSixRandom();//六位纯数字验证码
        String message = "【微米荟商城】您的验证码:"+captcha+" ，请勿泄露！感谢您的使用！";
        boolean sendResult= SmsEmayUtil.sendToSms("0",phone,message,"yzm","wmh",captcha);
        if(sendResult){
            renderJson(Ret.ok("info","发送成功!"));
        }else{
            renderJson(Ret.fail("info","发送失败!"));
        }
    }


    //绑定手机号码保存
    @Clear
    public void phoneapplysave() {
        Member member = getLoginMember();
        String phone = getPara("phone");
        String realname = getPara("realname");
        String idno = getPara("idno");
        String captcha = getPara("captcha");

        if(StrKit.isBlank(phone)){
            renderJson(Ret.fail("info","请输入正确的手机号!"));
            return;
        }
        /*if(StrKit.notBlank(phone)&&!RegexUtils.checkMobile(phone)){
            renderJson(Ret.fail("info","请输入正确的手机号!"));
            return;
        }*/

        if(CacheKit.get("sms",phone)==null){
            renderJson(Ret.fail("info","手机验证码已过期,请重新获取!"));
            return;
        }
        if(!captcha.equals(CacheKit.get("sms",phone).toString())){
            renderJson(Ret.fail("info","手机验证码不正确!"));
            return;
        }
        member.set("phone", phone);
        member.set("realname", realname);
        member.set("idno", idno);
        member.update();
        renderJson(Msg.SUCCESS);

    }

    //我的钱包
    public void capital() {
        Member member = getAttr("loginMember");
        setAttr("totalProfit", UserBalanceService.service.getBalance(member));
        wapTemplatePath("capital.html");


    }

    // 获取当前登录会员，若未登录则返回null
    public Member getLoginMember() {
        String id = getSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME);
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        Member loginMember = Member.dao.findById(id);
        return loginMember;
    }

    /**
     * 推荐二维码
     */
    @Clear
    public void recommendQrcode(){
       String code=getPara(0);
        if(StrKit.isBlank(code)){
            Member member=getLoginMember();
            code=IdGen.get().nextId(10);
            member.setCode(code);
            member.update();
        }
        String url= _Config.p.get("mall_web.url")+"/b/customer/wapRegisterForm/"+code;
        renderQrCode(url,180,180);
    }


    //用户注销
    @Clear
    public void logout() {

        //清除用户信息
        getRequest().getSession().removeAttribute(Member.LOGIN_MEMBER_ID_SESSION_NAME);
        Cookie loginMemberUsernameCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, null);
        Cookie loginTypeCookie = new Cookie(Member.LOGIN_TYPE_COOKIE_NAME, null);
        loginMemberUsernameCookie.setPath(getRequest().getContextPath() + "/");
        loginTypeCookie.setPath(getRequest().getContextPath() + "/");
        loginMemberUsernameCookie.setMaxAge(0);
        loginTypeCookie.setMaxAge(0);
        getResponse().addCookie(loginMemberUsernameCookie);
        getResponse().addCookie(loginTypeCookie);

        redirect("/index.html");


    }
}
